// 火星文计算
// 题目链接：https://fcqian.blog.csdn.net/article/details/127417952
// 做题思路：
// 用正则表达式，依次按照优先级，找到优先运算的左右两数，计算完成后将结果放入到结果队列中
class MarsCalc {
    constructor(calString) {
        this.calString = calString;
    }

    calculation() {
        let calc = this.calString;
        calc = this.replaceDollar(calc);
        calc = this.replaceID(calc);

        return calc;
    }

    replaceDollar(calculation) {
        const regex = /\d+\$\d+/g;
        let findStr = regex.exec(calculation);

        while (findStr != null) {
            let miniCal = this.calcDollar(findStr[0]);
            calculation = calculation.replace(regex, miniCal);

            findStr = regex.exec(calculation);
        }

        return calculation;
    }

    replaceID(calculation) {
        const regex = /\d+\#\d+/g;
        let findStr = regex.exec(calculation);

        while (findStr != null) {
            let miniCal = this.calcID(findStr[0]);
            calculation = calculation.replace(regex, miniCal);

            findStr = regex.exec(calculation);
        }

        return calculation;
    }

    calcDollar(str) {
        const regex = /\d+/g;
        const array = [...str.matchAll(regex)];
        const x = parseInt(array[0][0]);
        const y = parseInt(array[1][0]);

        return 3 * x + y + 2;
    }

    calcID(str) {
        const regex = /\d+/g;
        const array = [...str.matchAll(regex)];
        const x = parseInt(array[0][0]);
        const y = parseInt(array[1][0]);

        return 2 * x + 3 * y + 4;
    }
}

// test
['1#1', '1#2', '1$1', '1$2', '7#6$5#12'].forEach((ele) => {
    const mars = new MarsCalc(ele);
    console.log(`${ele} result is ${mars.calculation()}`);
});
